package com.yzt.message.custom;

import android.os.Parcel;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yzt.zhuju.network.entity.message.RedBean;
import com.yzt.zhuju.rongyun.IMMessageType;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

import io.rong.common.ParcelUtils;
import io.rong.imlib.MessageTag;
import io.rong.imlib.model.MessageContent;

/**
 * 红包消息
 */
@MessageTag(value = IMMessageType.RED_PKG_MESSAGE, flag = MessageTag.ISPERSISTED | MessageTag.ISCOUNTED)
public class RXRedPkgMessageContent extends MessageContent {

    private String content;

    private RedBean messageExtra;

    public static RXRedPkgMessageContent setGiftMessageData(String content, RedBean extra) {
        RXRedPkgMessageContent mRXMessageContent = new RXRedPkgMessageContent();
        mRXMessageContent.content = content;
        mRXMessageContent.messageExtra = extra;
        return mRXMessageContent;
    }

    @Override
    public byte[] encode() {
        JSONObject object = new JSONObject();
        object.put("content", content);
        object.put("messageExtra", messageExtra);
        return object.toString().getBytes(StandardCharsets.UTF_8);

    }

    public RXRedPkgMessageContent() {
    }

    public RXRedPkgMessageContent(byte[] data) {
        super(data);
        String jsonStr = null;
        try {
            jsonStr = new String(data, StandardCharsets.UTF_8);
            JSONObject object = JSON.parseObject(jsonStr);
            setContent(object.getString("content"));
            setMessageExtra(JSONObject.parseObject(object.getString("messageExtra"), RedBean.class));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        ParcelUtils.writeToParcel(dest, content);
        ParcelUtils.writeToParcel(dest, messageExtra);
    }

    public static final Creator<RXRedPkgMessageContent> CREATOR = new Creator<RXRedPkgMessageContent>() {

        @Override
        public RXRedPkgMessageContent createFromParcel(Parcel source) {
            return new RXRedPkgMessageContent(source);
        }

        @Override
        public RXRedPkgMessageContent[] newArray(int size) {
            return new RXRedPkgMessageContent[size];
        }
    };

    public RXRedPkgMessageContent(Parcel parcel) {
        content = ParcelUtils.readFromParcel(parcel);
        messageExtra = parcel.readParcelable(RedBean.class.getClassLoader());
    }

    @Override
    public int describeContents() {
        return 0;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public RedBean getMessageExtra() {
        return messageExtra;
    }

    public void setMessageExtra(RedBean messageExtra) {
        this.messageExtra = messageExtra;
    }
}
